package model;

import exception.ScoreException;

public class Score {
    private Student student;  // 学生对象
    private Course course;    // 课程对象
    private double score;     // 分数

    public Score(Student student, Course course, double score) throws ScoreException {
        this.student = student;
        this.course = course;
        setScore(score);  // 通过setter进行验证
    }

    // Getter和Setter方法
    public Student getStudent() { return student; }
    public Course getCourse() { return course; }
    public double getScore() { return score; }

    /**
     * 设置分数，包含异常处理
     */
    public void setScore(double score) throws ScoreException {
        if (score < 0 || score > 100) {
            throw new ScoreException("分数必须在0-100之间，当前分数：" + score);
        }
        this.score = score;
    }

    @Override
    public String toString() {
        return student.getId() + "," + course.getCode() + "," + score;
    }

    // 从字符串解析Score对象
    public static Score fromString(String data, java.util.Map<String, Student> students,
                                   java.util.Map<String, Course> courses) throws ScoreException {
        String[] parts = data.split(",");
        if (parts.length == 3) {
            Student student = students.get(parts[0]);
            Course course = courses.get(parts[1]);
            if (student != null && course != null) {
                return new Score(student, course, Double.parseDouble(parts[2]));
            }
        }
        return null;
    }
}